package com.java1412.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.java1412.config.OssConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author java1412
 * @create 2021-07-20 13:59
 */
@Component
public class AliyunOssUtil {
    @Autowired
    private OssConfig config;

    public String upload(File file) {
        if (null == file) {
            return null;
        }
        String endPoint = config.getEndPoint();
        String accessKeyId = config.getAccessKeyId();
        String accessKeySecret = config.getAccessKeySecret();
        String bucketName = config.getBucketName();
        String filehost = config.getFilehost();
        // 定义子文件的格式
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = df.format(new Date());
        // 阿里云文件上传客户端
        OSSClient client = new OSSClient(endPoint, accessKeyId, accessKeySecret);
        try {
            // 判断桶是否存在
            if (!client.doesBucketExist(bucketName)) {
                // 创建桶
                client.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                // 设置访问权限为公共读
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                // 发起创建桶的请求
                client.createBucket(createBucketRequest);
            }
            // 当桶存在时，进行文件上传
            // 设置文件路径和名称
            String fileUrl = filehost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());
            PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            // 文件上传成功后，返回当前文件的路径
            if (null != result) {
                return fileUrl;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != client) {
                client.shutdown();
            }
        }
        return null;
    }
}
